package games.mapacman.server;

import games.mapacman.common.*;
import games.mapacman.common.consts;

import java.util.Random;
import java.util.Vector;
import marauroa.common.game.IRPZone;
import marauroa.common.game.RPObject;
import marauroa.common.game.RPObject.ID;
import marauroa.server.game.rp.MarauroaRPZone;
import marauroa.server.game.rp.RPWorld;
import marauroa.server.game.Statistics;


public class MaPacmanRPWorld extends RPWorld
  {
	private Vector<RPObject> Players;
	private Statistics stats;
	private Random randomGen;
	private int GhostMoveInt=10;
	protected static MaPacmanRPWorld instance;
	
	public MaPacmanRPWorld()
	{
		super();
		randomGen = new Random();
		common.initRPClasses();
		Players = new Vector<RPObject>();
		MarauroaRPZone zone = new MarauroaRPZone("start");
		addRPZone(zone);
	}
	

	public void removePlayer(ID id)
	{
		RPObject player = this.get(id);	
		((MaPacmanZone)getRPZone(id)).removePlayer(player);
		Players.remove(player);
		this.remove(id);
	}
	
	public boolean addPlayer(RPObject object)
	{
		// set GhostMoveInt, that Ghosts move 100turns after last player has left
		GhostMoveInt=100;
		
		for(IRPZone RPzone : this)
		{
			MaPacmanZone zone = (MaPacmanZone) RPzone; 
			if (zone.getName().equals(object.get("zoneid")))
			{
				this.add(object);
				zone.addPlayer(object);	
				object.put("type",consts.TYPE_PLAYER);
				return Players.add(object);
			}
		}
		return false;
	}
	
	public Vector<RPObject> getPlayers()
	{
		return Players;		
	}

	public void beginTurn() {
		for(IRPZone RPzone : this)
		{
			MaPacmanZone zone = (MaPacmanZone) RPzone;
			zone.beginTurn();
		}
		
	}

	public boolean hasPlayer(RPObject newPlayer) {
		for(IRPZone RPzone : this)
		{
			for (RPObject player : ((MaPacmanZone) RPzone).getPlayers())
			{
				if (player.get("name").equals(newPlayer.get("name"))) return true;
			}
		}
		return false;
	}

	public void setStats(Statistics stats) {
		this.stats = stats;
		
	}
	
	public Statistics getStats()
	{
		return stats;
	}


	public void changeZone(RPObject object, MaPacmanZone oldzone, String newZoneName) {
		if (object.get("type").equals(consts.TYPE_PLAYER))
		{
			oldzone.removePlayer(object);
			for(IRPZone RPzone : this)
			{
				MaPacmanZone zone = (MaPacmanZone) RPzone; 
				if (zone.getName().equals(newZoneName))
				{
					changeZone(zone.getID(),object);
					zone.addPlayer(object);	
				}
			}
		}
	}


	public Random getRandom() {
		return randomGen;
	}


	public boolean moveGhosts() {
		if (Players.size()>0) return true;
		else if (GhostMoveInt>0) 
		{
			GhostMoveInt--;
			return true;
		}

		return false;
	}

	public static MaPacmanRPWorld get() {
		synchronized(MaPacmanRPWorld.class) {
			if (instance == null) {
				instance = new MaPacmanRPWorld();
			}
		}
		return instance;
	}
	
  }
